package com.fan89.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fan89.common.lang.Result;
import com.fan89.dto.CommentListDto;
import com.fan89.dto.LinkListDto;
import com.fan89.entity.Comment;
import com.fan89.entity.User;
import com.fan89.service.CommentService;
import com.fan89.service.UserService;
import com.fan89.util.CheckUtil;
import com.fan89.util.ShiroUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongbiao.fan
 * @since 2020-07-29
 */
@Api(value = "评论管理api",tags = "评论管理相关接口")
@RestController
public class CommentController {

    @Autowired
    CommentService commentService;
    @Autowired
    UserService userService;

    @Value("${baseUrl}")
    private String baseUrl;

//    public static void main(String[] args) {
//        System.out.println(baseUrl);
//    }

    /**
     * 评论列表
     *
     * @param
     * @return
     */
    @ApiOperation("评论列表")
    @GetMapping("/comments")
    public Result list() {

        List<Comment> list = commentService.list();
        List<CommentListDto> dtoList = new ArrayList<>(list.size());
        for (Comment comment : list) {
            CommentListDto listDto = new CommentListDto();
            BeanUtil.copyProperties(comment, listDto);
            dtoList.add(listDto);
        }
        LinkListDto listDto = new LinkListDto();
        BeanUtil.copyProperties(list, listDto);
        return Result.success("成功获取全部评论数据", dtoList);
    }

    /**
     * 评论详情
     *
     * @param id
     * @return
     */
    @ApiOperation("评论详情")
    @GetMapping("/comment/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {

        Comment comment = commentService.getById(id);
        Assert.notNull(comment, "本评论已被删除");
        return Result.success("成功读取评论数据", comment);
    }



    //    @RequiresAuthentication //认证后方可访问该接口
    @ApiOperation("评论新增")
    @PostMapping("/comment/add")
    public Result add(@Validated @RequestBody Comment comment) {
        Comment temp = new Comment();
        Long currentUserId = null;
        try {
            currentUserId = ShiroUtils.getProfile().getId().longValue(); //获取当前用户id
        } catch (Exception e) {
            e.printStackTrace();
        }
//        Long currentUserId=null;
        if (currentUserId != null) {
            User user = userService.getOne(new QueryWrapper<User>().eq("id", currentUserId));
            BeanUtil.copyProperties(comment, temp, "id", "create_time");
            comment.setAdminComment(true);
            comment.setAvatar(user.getAvatar());
            comment.setEmail(user.getEmail());
            comment.setNickname(user.getNickname());
            commentService.save(comment);
            return Result.success("留言成功");
        } else {
            CheckUtil checkUtil=new CheckUtil();
            if(!checkUtil.isEmail(comment.getEmail())){
                return Result.error("邮箱格式不正确");
            }
            Random random = new Random();
            Integer result = random.nextInt(5);
            Integer randomAvatar = result + 1;
            comment.setAvatar(baseUrl + "/img/avatar/" + randomAvatar.toString() + ".jpg");
            BeanUtil.copyProperties(comment, temp, "id", "create_time");
            commentService.saveOrUpdate(temp);
            return Result.success("留言成功");
        }

    }

    /**
     * 评论编辑
     *
     * @param
     * @return
     */
    @ApiOperation("标签编辑")
    @RequiresAuthentication //认证后方可访问该接口
    @PostMapping("/comment/edit")
    public Result edit(@Validated @RequestBody Comment comment) {

        Comment temp = null;
        Long currentUserId = ShiroUtils.getProfile().getId().longValue(); //获取当前用户id
        if (comment.getId() != null) {
            temp = commentService.getById(comment.getId());
//            Assert.isTrue(temp.getUserId().longValue()==currentUserId,"无编辑权限");
        } else {
            //初始化新文章
            temp = new Comment();
        }
        //复制文章数据
        BeanUtil.copyProperties(comment, temp, "id", "create_time");

        commentService.saveOrUpdate(temp);
        return Result.success("成功编辑或创建留言");
    }

    /**
     * 评论删除
     *
     * @param id
     * @return
     */
    @ApiOperation("评论删除")
    @GetMapping("/comment/delete/{id}")
    public Result delete(@PathVariable(name = "id") String id) {
//        Long currentUserId = ShiroUtils.getProfile().getId().longValue();
//        if(currentUserId==null&&currentUserId!=1L){
//            return Result.error("抱歉，您没有删除权限");
//        }
        boolean result = commentService.removeById(id);// 据库中为Long id
        Assert.isTrue(result, "本留言已被删除");
        return Result.success("成功删除本留言");
    }

}
